/**
 * Copyright (c) Huawei Technologies Co., Ltd. 1987-2021. All rights reserved.
*/

package com.gitee.fufu669.utils;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// 注解
@SuppressWarnings({ "unchecked" })
/** @author wangfupeng */
/**
 * TODO
*/
public class CacheJsonUtil {

    /**
     * TODO
    */
    public static final Logger logger = LoggerFactory.getLogger(CacheJsonUtil.class);

    // 创建
    private static ThreadLocal<ObjectMapper> objMapperLocal = new ThreadLocal<ObjectMapper>() {
        // 覆盖父类方法的注解
        @Override
        /**
         * TODO
        */
        public ObjectMapper initialValue() {
            // 创建
            ObjectMapper mapper = new ObjectMapper();
            // 返回
            return mapper;
        }
    };

    /**
     * TODO
    */
    public static <T> String toJson(T obj) {
        // 返回
        return JSON.toJSONString(obj);
    }

    /**
     * TODO
    */
    public static <T> T toObject(String jsonStr, Class<T> cls) {
        // 返回
        return JSON.parseObject(jsonStr, cls);
    }

    /**
     * TODO
    */
    public static <T> T toObject(Object jsonObject, Class<T> cls) {
        // 返回
        return JSON.parseObject(toJson(jsonObject), cls);
    }

    
    /**
     * TODO
    */
    public static <T> List<T> toList(String jsonString, Class<T> clazz) {
        // 尝试下面的代码
        try {
            // 拿出
            ObjectMapper mapper = objMapperLocal.get();
            // 返回
            return (List<T>) mapper.readValue(jsonString, mapper.getTypeFactory()
                    // TODO
                    .constructParametricType(List.class, clazz));
        // 捕捉异常
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
        }
        // 返回
        return new ArrayList<>();
    }

}
